<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Android," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.2" />






<meta name="description" content="上一篇学习了okhttp的入门篇，这一篇学习的retrofit底层默认使用的就是okhttp，相信大家多少也听过这个框架，下面我们就来一起学习下，讲真，学会之后这个框架用起来真的很爽，特别灵活。 按照习惯先来说一下它的优缺点 优点：  可以配置不同HTTP client来实现网络请求，如okhttp、httpclient等 请求的方法参数注解都可以定制 支持同步、异步和RxJava 超级解耦 可以">
<meta name="keywords" content="Android">
<meta property="og:type" content="article">
<meta property="og:title" content="你必须了解的网络框架Retrofit2.0">
<meta property="og:url" content="http://soaic.github.io/2016/09/05/2016-09-05-Retrofit/index.html">
<meta property="og:site_name" content="Soaic&#39;s Blog">
<meta property="og:description" content="上一篇学习了okhttp的入门篇，这一篇学习的retrofit底层默认使用的就是okhttp，相信大家多少也听过这个框架，下面我们就来一起学习下，讲真，学会之后这个框架用起来真的很爽，特别灵活。 按照习惯先来说一下它的优缺点 优点：  可以配置不同HTTP client来实现网络请求，如okhttp、httpclient等 请求的方法参数注解都可以定制 支持同步、异步和RxJava 超级解耦 可以">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2017-08-17T17:43:03.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="你必须了解的网络框架Retrofit2.0">
<meta name="twitter:description" content="上一篇学习了okhttp的入门篇，这一篇学习的retrofit底层默认使用的就是okhttp，相信大家多少也听过这个框架，下面我们就来一起学习下，讲真，学会之后这个框架用起来真的很爽，特别灵活。 按照习惯先来说一下它的优缺点 优点：  可以配置不同HTTP client来实现网络请求，如okhttp、httpclient等 请求的方法参数注解都可以定制 支持同步、异步和RxJava 超级解耦 可以">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://soaic.github.io/2016/09/05/2016-09-05-Retrofit/"/>





  <title>你必须了解的网络框架Retrofit2.0 | Soaic's Blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Soaic's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">Soaic</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-music">
          <a href="/music/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-music"></i> <br />
            
            音乐
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://soaic.github.io/2016/09/05/2016-09-05-Retrofit/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Soaic">
      <meta itemprop="description" content="Welcome!">
      <meta itemprop="image" content="/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Soaic's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">你必须了解的网络框架Retrofit2.0</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2016-09-05T22:04:00+08:00">
                2016-09-05
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Android框架/" itemprop="url" rel="index">
                    <span itemprop="name">Android框架</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2016/09/05/2016-09-05-Retrofit/" class="leancloud_visitors" data-flag-title="你必须了解的网络框架Retrofit2.0">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数 </span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>上一篇学习了okhttp的入门篇，这一篇学习的retrofit底层默认使用的就是okhttp，相信大家多少也听过这个框架，下面我们就来一起学习下，讲真，学会之后这个框架用起来真的很爽，特别灵活。</p>
<p>按照习惯先来说一下它的优缺点</p>
<h3 id="优点："><a href="#优点：" class="headerlink" title="优点："></a>优点：</h3><blockquote>
<ol>
<li>可以配置不同HTTP client来实现网络请求，如okhttp、httpclient等</li>
<li>请求的方法参数注解都可以定制</li>
<li>支持同步、异步和RxJava</li>
<li>超级解耦</li>
<li>可以配置不同的反序列化工具来解析数据，如json、xml等</li>
<li>使用非常方便灵活</li>
<li>框架使用了很多设计模式(感兴趣的可以看看源码学习学习)</li>
</ol>
</blockquote>
<h3 id="缺点："><a href="#缺点：" class="headerlink" title="缺点："></a>缺点：</h3><blockquote>
<ol>
<li>不能接触序列化实体和响应数据</li>
<li>执行的机制太严格</li>
<li>使用转换器比较低效</li>
<li>只能支持简单自定义参数类型</li>
</ol>
</blockquote>
<a id="more"></a>
<h3 id="相关学习资料的网址"><a href="#相关学习资料的网址" class="headerlink" title="相关学习资料的网址"></a>相关学习资料的网址</h3><ol>
<li>retrofit官网：<a href="http://square.github.io/retrofit/" target="_blank" rel="external">http://square.github.io/retrofit/</a></li>
<li>github地址：<a href="https://github.com/square/retrofit" target="_blank" rel="external">https://github.com/square/retrofit</a></li>
<li>Simple HTTP with Retrofit2:<br><a href="https://realm.io/news/droidcon-jake-wharton-simple-http-retrofit-2/" target="_blank" rel="external">https://realm.io/news/droidcon-jake-wharton-simple-http-retrofit-2/</a></li>
</ol>
<h3 id="环境配置"><a href="#环境配置" class="headerlink" title="环境配置"></a>环境配置</h3><p>在builde.gradle里面添加上</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line">compile <span class="string">'com.squareup.retrofit2:retrofit:2.1.0'</span></div><div class="line">compile <span class="string">'com.squareup.retrofit2:converter-gson:2.1.0'</span></div><div class="line">compile <span class="string">'com.squareup.okhttp3:okhttp:3.4.1'</span></div></pre></td></tr></table></figure>
<p>在AndroidManifest.xml添加所需权限</p>
<figure class="highlight xml"><table><tr><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">uses-permission</span> <span class="attr">android:name</span>=<span class="string">"android.permission.INTERNET"</span> /&gt;</span></div></pre></td></tr></table></figure>
<h3 id="基本使用"><a href="#基本使用" class="headerlink" title="基本使用"></a>基本使用</h3><ul>
<li>get异步请求</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">GitHubService</span> </span>&#123;</div><div class="line">  <span class="meta">@GET</span>(<span class="string">"users/&#123;user&#125;/repos"</span>)</div><div class="line">  <span class="function">Call&lt;ResponseBody&gt; <span class="title">listRepos</span><span class="params">(@Path(<span class="string">"user"</span>)</span> String user)</span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line">Retrofit retrofit = <span class="keyword">new</span> Retrofit.Builder()</div><div class="line">    .baseUrl(<span class="string">"https://api.github.com/"</span>)</div><div class="line">    .addConverterFactory(GsonConverterFactory.create()) </div><div class="line">    .build();</div><div class="line">GitHubService service = retrofit.create(GitHubService.class);</div><div class="line">Call&lt;ResponseBody&gt; repos = service.listRepos(<span class="string">"octocat"</span>);</div><div class="line">repos.enqueue(<span class="keyword">new</span> Callback&lt;ResponseBody&gt;() &#123;</div><div class="line">            <span class="meta">@Override</span></div><div class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onResponse</span><span class="params">(Call&lt;ResponseBody&gt; call, Response&lt;ResponseBody&gt; response)</span> </span>&#123;</div><div class="line">                Log.e(<span class="string">"APP"</span>,response.body().source().toString());</div><div class="line">            &#125;</div><div class="line">            <span class="meta">@Override</span></div><div class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onFailure</span><span class="params">(Call&lt;ResponseBody&gt; call, Throwable t)</span> </span>&#123;</div><div class="line">            	t.printStackTrace();</div><div class="line">            &#125;</div><div class="line">        &#125;);</div></pre></td></tr></table></figure>
<p><code>.baseUrl</code>设置最基本url,也就是http请求的url前缀,可以把项目中重复的前缀用这个来设置</p>
<p><code>.addConverterFactory(GsonConverterFactory.create())</code>是添加Gson数据解析ConverterFactory,后面会专门介绍下这个，这里就不做过多解释</p>
<p><code>ResponseBody</code> 这个是okhttp里面的对象，可以直接返回整个字符串，也可以获取流的形式</p>
<ul>
<li>post异步请求</li>
</ul>
<p>POST与GET实现基本上是一样的，只是把注解GET换成POST就OK.为了测试POST，专门去网上找了个接口测试，下面就分享给大家,既可以用GET也可以用POST请求</p>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line">http:<span class="comment">//www.kuaidi100.com/query?type=快递公司代号&amp;postid=快递单号</span></div></pre></td></tr></table></figure>
<p>快递公司编码:<br>申通=”shentong”<br>EMS=”ems”<br>顺丰=”shunfeng”<br>圆通=”yuantong”<br>中通=”zhongtong”<br>韵达=”yunda”<br>天天=”tiantian”<br>汇通=”huitongkuaidi”<br>全峰=”quanfengkuaidi”<br>德邦=”debangwuliu”<br>宅急送=”zhaijisong”  </p>
<p>拿着这个接口来实现一下POST异步请求</p>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">GitHubService</span> </span>&#123;</div><div class="line">    <span class="meta">@POST</span>(<span class="string">"query"</span>)</div><div class="line">    <span class="function">Call&lt;PostQueryInfo&gt; <span class="title">search</span><span class="params">(@Query(<span class="string">"type"</span>)</span> String type, @<span class="title">Query</span><span class="params">(<span class="string">"postid"</span>)</span> String postid)</span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PostQueryInfo</span> </span>&#123;</div><div class="line">    <span class="keyword">private</span> String message;</div><div class="line">    <span class="keyword">private</span> String nu;</div><div class="line">    <span class="keyword">private</span> String ischeck;</div><div class="line">    <span class="keyword">private</span> String com;</div><div class="line">    <span class="keyword">private</span> String status;</div><div class="line">    <span class="keyword">private</span> String condition;</div><div class="line">    <span class="keyword">private</span> String state;</div><div class="line">    <span class="keyword">private</span> List&lt;DataBean&gt; data;</div><div class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">DataBean</span> </span>&#123;</div><div class="line">        <span class="keyword">private</span> String time;</div><div class="line">        <span class="keyword">private</span> String context;</div><div class="line">        <span class="keyword">private</span> String ftime;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line">Retrofit retrofit = <span class="keyword">new</span> Retrofit.Builder()</div><div class="line">        .baseUrl(<span class="string">"http://www.kuaidi100.com/"</span>)</div><div class="line">        .addConverterFactory(GsonConverterFactory.create()) </div><div class="line">        .build();</div><div class="line">GitHubService apiService = retrofit.create(GitHubService.class);</div><div class="line">Call&lt;PostQueryInfo&gt; call = apiService.search(<span class="string">"yuantong"</span>,<span class="string">"500379523313"</span>);</div><div class="line">call.enqueue(<span class="keyword">new</span> Callback&lt;PostQueryInfo&gt;()&#123;</div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onResponse</span><span class="params">(Call&lt;PostQueryInfo&gt; call,Response&lt;PostQueryInfo&gt; response)</span></span>&#123;</div><div class="line">         Log.e(<span class="string">"APP"</span>,response.body().getNu());</div><div class="line">    &#125;</div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onFailure</span><span class="params">(Call&lt;PostQueryInfo&gt; call,Throwable t)</span></span>&#123;</div><div class="line">        t.printStackTrace();</div><div class="line">    &#125;</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<p>PostQueryInfo实体类省略了get和set方法，大家可以自行快捷键，最终打印返回回来的快递单号，实现POST异步请求就是这么简单</p>
<p><code>http://www.bejson.com/knownjson/webInterface/</code>这网站里面还有一些其它免费接口，感兴趣的可以去看看</p>
<ul>
<li>常用注解的使用介绍</li>
</ul>
<p>上面GitHubService里面的注解大家应该都能猜它的作用了吧，下面就给大家介绍下</p>
<p><code>@GET</code>和<code>@POST</code>分别是get和post请求。括号里面的value值与上面<code>.baseUrl</code>组成完整的路径</p>
<p><code>@Path</code>动态的URL访问。像上面get请求中的<code>{user}</code>可以把它当做一个占位符，通过<code>@Path(&quot;user&quot;)</code>标注的参数进行替换</p>
<p><code>@Query</code>请求参数。无论是GET或POST的参数都可以用它来实现</p>
<p><code>@QueryMap</code>请求参数使用Map集合。可以传递一个map集合对象</p>
<p><code>@Body</code>实体请求参数。顾名思义可以传递一个实体对象来作为请求的参数，不过实体属性要与参数名一一致</p>
<p><code>@FormUrlEncoded</code>和<code>@Field</code>简单的表单键值对。两个需要结合使用，使用如下：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="meta">@FormUrlEncoded</span></div><div class="line"><span class="meta">@POST</span>(<span class="string">"user/edit"</span>)</div><div class="line"><span class="function">Call&lt;User&gt; <span class="title">updateUser</span><span class="params">(@Field(<span class="string">"first_name"</span>)</span> String first, @<span class="title">Field</span><span class="params">(<span class="string">"last_name"</span>)</span> String last)</span>;</div></pre></td></tr></table></figure>
<p><code>@Multipart</code>和<code>@Part</code>POST表单的方式上传文件可以携带参数。两个需要结合使用，使用方式查看下面<strong>文件上传</strong>中介绍。</p>
<p><code>@PartMap</code>和<code>@Part</code>POST表单上传多个文件携带参数。两个结合使用，使用方式查看下面<strong>文件上传</strong>中介绍。</p>
<p>这里只介绍了一些常用的，大家如果想了解更多可以查看相关文档</p>
<ul>
<li>文件上传<br>1、<strong>单文件上传携带参数</strong>(使用注解<code>@Multipart</code>和<code>@Part</code>)，需要在手机SD卡目录下的Pictures文件夹下添加xuezhiqian.png图片</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="meta">@Multipart</span></div><div class="line"><span class="meta">@POST</span>(<span class="string">"UploadServlet"</span>)</div><div class="line"><span class="function">Call&lt;ResponseBody&gt; <span class="title">uploadfile</span><span class="params">(@Part MultipartBody.Part photo, @Part(<span class="string">"username"</span>)</span> RequestBody username, @<span class="title">Part</span><span class="params">(<span class="string">"password"</span>)</span> RequestBody password)</span>;</div></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line">Retrofit retrofitUpload = <span class="keyword">new</span> Retrofit.Builder()</div><div class="line">                .baseUrl(<span class="string">"http://192.168.1.8:8080/UploadFile/"</span>)</div><div class="line">                .addConverterFactory(GsonConverterFactory.create())</div><div class="line">                .build();</div><div class="line">GitHubService service = retrofitUpload.create(GitHubService.class);</div><div class="line">File file = <span class="keyword">new</span> File(Environment.getExternalStorageDirectory()+<span class="string">"/Pictures"</span>, <span class="string">"xuezhiqian.png"</span>);</div><div class="line"><span class="comment">//设置Content-Type:application/octet-stream</span></div><div class="line">RequestBody photoRequestBody = RequestBody.create(MediaType.parse(<span class="string">"application/octet-stream"</span>), file);</div><div class="line"><span class="comment">//设置Content-Disposition:form-data; name="photo"; filename="xuezhiqian.png"</span></div><div class="line">MultipartBody.Part photo = MultipartBody.Part.createFormData(<span class="string">"photo"</span>, file.getName(), photoRequestBody);</div><div class="line"><span class="comment">//添加参数用户名和密码，并且是文本类型</span></div><div class="line">RequestBody userName = RequestBody.create(MediaType.parse(<span class="string">"text/plain"</span>), <span class="string">"abc"</span>);</div><div class="line">RequestBody passWord = RequestBody.create(MediaType.parse(<span class="string">"text/plain"</span>), <span class="string">"123"</span>); </div><div class="line">Call&lt;ResponseBody&gt; loadCall = service.uploadfile(photo, userName,passWord);</div><div class="line">loadCall.enqueue(<span class="keyword">new</span> Callback&lt;ResponseBody&gt;() &#123;</div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onResponse</span><span class="params">(Call&lt;ResponseBody&gt; call, Response&lt;ResponseBody&gt; response)</span> </span>&#123;</div><div class="line">        Log.e(<span class="string">"APP"</span>, response.body().source().toString());</div><div class="line">    &#125;</div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onFailure</span><span class="params">(Call&lt;ResponseBody&gt; call, Throwable t)</span> </span>&#123;</div><div class="line">        t.printStackTrace();</div><div class="line">    &#125;</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<p>2、<strong>多文件上传携带参数</strong>(使用注解<code>@PartMap</code>和<code>@Part</code>),需要再在手机SD卡目录下的Pictures文件夹下添加xuezhiqian2.png图片</p>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="meta">@Multipart</span></div><div class="line"><span class="meta">@POST</span>(<span class="string">"UploadServlet"</span>)</div><div class="line"><span class="function">Call&lt;ResponseBody&gt; <span class="title">uploadfile</span><span class="params">(@PartMap Map&lt;String, RequestBody&gt; params,  @Part(<span class="string">"password"</span>)</span> RequestBody password)</span>;</div></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line">Retrofit retrofitUpload = <span class="keyword">new</span> Retrofit.Builder()</div><div class="line">                .baseUrl(<span class="string">"http://192.168.1.8:8080/UploadFile/"</span>)</div><div class="line">                .addConverterFactory(GsonConverterFactory.create())</div><div class="line">                .build();</div><div class="line">GitHubService service = retrofitUpload.create(GitHubService.class);</div><div class="line">File file = <span class="keyword">new</span> File(Environment.getExternalStorageDirectory()+<span class="string">"/Pictures"</span>, <span class="string">"xuezhiqian.png"</span>);</div><div class="line">File file2 = <span class="keyword">new</span> File(Environment.getExternalStorageDirectory()+<span class="string">"/Pictures"</span>, <span class="string">"xuezhiqian2.png"</span>);</div><div class="line">RequestBody photoRequestBody = RequestBody.create(MediaType.parse(<span class="string">"application/octet-stream"</span>), file);</div><div class="line">RequestBody photoRequestBody2 = RequestBody.create(MediaType.parse(<span class="string">"application/octet-stream"</span>), file2);  </div><div class="line">RequestBody userName = RequestBody.create(MediaType.parse(<span class="string">"text/plain"</span>), <span class="string">"abc"</span>);</div><div class="line">RequestBody passWord = RequestBody.create(MediaType.parse(<span class="string">"text/plain"</span>), <span class="string">"123"</span>); </div><div class="line">Map&lt;String,RequestBody&gt; photos = <span class="keyword">new</span> HashMap&lt;&gt;();</div><div class="line"><span class="comment">//添加文件一</span></div><div class="line">photos.put(<span class="string">"photos\"; filename=\""</span>+file.getName(), photoRequestBody);</div><div class="line"><span class="comment">//添加文件二</span></div><div class="line">photos.put(<span class="string">"photos\"; filename=\""</span>+file2.getName(), photoRequestBody2);</div><div class="line"><span class="comment">//添加用户名参数</span></div><div class="line">photos.put(<span class="string">"username"</span>,  userName);</div><div class="line">Call&lt;ResponseBody&gt; loadCall = service.uploadfile(photos, passWord);</div><div class="line">loadCall.enqueue(<span class="keyword">new</span> Callback&lt;ResponseBody&gt;() &#123;</div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onResponse</span><span class="params">(Call&lt;ResponseBody&gt; call, Response&lt;ResponseBody&gt; response)</span> </span>&#123;</div><div class="line">        Log.e(<span class="string">"APP"</span>, response.body().source().toString());</div><div class="line">    &#125;</div><div class="line">    <span class="meta">@Override</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onFailure</span><span class="params">(Call&lt;ResponseBody&gt; call, Throwable t)</span> </span>&#123;</div><div class="line">        t.printStackTrace();</div><div class="line">    &#125;</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<p>要说明的是，多个文件上传不能像单个文件上传使用<code>MultipartBody.Part</code>对象，而是使用注解<code>@PartMap</code>添加多个RequestBody拼接filename来实现，<code>@part(&quot;?&quot;)</code>和<code>@Multipart</code>注解已经帮我们设置好成<code>Content-Disposition:form-data; name=&quot;?&quot;</code>这样子了，<code>@part</code>里的问号对应<code>name</code>后面的问号，而我们要添加多个文件，则需要在name里面作文章。所以就有了上面MAP集合中的KEY的拼接字符串，我们想设置成<code>Content-Disposition:form-data; name=&quot;photo&quot;; filename=&quot;xuezhiqian.png&quot;</code>,MAP集合KEY的值设置为<code>photo&quot;; filename=&quot;xuezhiqian.png</code>替换name后面的问号就OK了,里面的引号在使用的时候需要加上反斜杠转义嵌套使用。</p>
<p>多文件上传携带参数，参考自：<br><a href="http://blog.csdn.net/jdsjlzx/article/details/52246114" target="_blank" rel="external">http://blog.csdn.net/jdsjlzx/article/details/52246114</a></p>
<p>一直找不到免费上传文件的接口来做测试，我就花了点时间自己做了一个，代码也是参考网上的，这里也给大家贴一下后台核心接收文件保存的代码，希望对大家有所帮助，自己动手丰衣足食。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"><span class="comment"> * 上传文件</span></div><div class="line"><span class="comment"> * <span class="doctag">@param</span> request</span></div><div class="line"><span class="comment"> * <span class="doctag">@param</span> response</span></div><div class="line"><span class="comment"> * <span class="doctag">@throws</span> IOException</span></div><div class="line"><span class="comment"> */</span></div><div class="line"><span class="meta">@SuppressWarnings</span>(<span class="string">"unchecked"</span>)</div><div class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">uploadFile</span><span class="params">(HttpServletRequest request, HttpServletResponse response)</span> <span class="keyword">throws</span> IOException </span>&#123;</div><div class="line">	response.setContentType(<span class="string">"text/html;charset=utf-8"</span>);<span class="comment">// 设置响应编码</span></div><div class="line">	request.setCharacterEncoding(<span class="string">"utf-8"</span>);</div><div class="line">	PrintWriter writer = response.getWriter();<span class="comment">// 获取响应输出流</span></div><div class="line">	<span class="comment">//ServletInputStream inputStream = request.getInputStream();// 获取请求输入流</span></div><div class="line">	<span class="comment">/*</span></div><div class="line"><span class="comment">	 * 1、创建DiskFileItemFactory对象，设置缓冲区大小和临时文件目录 该类有两个构造方法一个是无参的构造方法，</span></div><div class="line"><span class="comment">	 * 另一个是带两个参数的构造方法</span></div><div class="line"><span class="comment">	 * </span></div><div class="line"><span class="comment">	 * @param int sizeThreshold,该参数设置内存缓冲区的大小，默认值为10K。当上传文件大于缓冲区大小时，</span></div><div class="line"><span class="comment">	 * fileupload组件将使用临时文件缓存上传文件</span></div><div class="line"><span class="comment">	 * </span></div><div class="line"><span class="comment">	 * @param java.io.File</span></div><div class="line"><span class="comment">	 * repository,该参数指定临时文件目录，默认值为System.getProperty("java.io.tmpdir");</span></div><div class="line"><span class="comment">	 * </span></div><div class="line"><span class="comment">	 * 如果使用了无参的构造方法，则使用setSizeThreshold(int</span></div><div class="line"><span class="comment">	 * sizeThreshold),setRepository(java.io.File repository) 方法手动进行设置</span></div><div class="line"><span class="comment">	 */</span></div><div class="line">	DiskFileItemFactory factory = <span class="keyword">new</span> DiskFileItemFactory();</div><div class="line">	<span class="keyword">int</span> sizeThreshold = <span class="number">1024</span> * <span class="number">1024</span>;</div><div class="line">	factory.setSizeThreshold(sizeThreshold);</div><div class="line">	File repository = <span class="keyword">new</span> File(request.getSession().getServletContext().getRealPath(<span class="string">"temp"</span>));</div><div class="line">	<span class="comment">// System.out.println(request.getSession().getServletContext().getRealPath("temp"));</span></div><div class="line">	<span class="comment">// System.out.println(request.getRealPath("temp"));</span></div><div class="line">	factory.setRepository(repository);</div><div class="line">	<span class="comment">/*</span></div><div class="line"><span class="comment">	 * 2、使用DiskFileItemFactory对象创建ServletFileUpload对象，并设置上传文件的大小</span></div><div class="line"><span class="comment">	 * </span></div><div class="line"><span class="comment">	 * ServletFileUpload对象负责处理上传的文件数据，并将表单中每个输入项封装成一个FileItem 该对象的常用方法有：</span></div><div class="line"><span class="comment">	 * boolean isMultipartContent(request);判断上传表单是否为multipart/form-data类型</span></div><div class="line"><span class="comment">	 * List parseRequest(request);解析request对象，并把表单中的每一个输入项包装成一个fileItem</span></div><div class="line"><span class="comment">	 * 对象，并返回一个保存了所有FileItem的list集合 void setFileSizeMax(long</span></div><div class="line"><span class="comment">	 * filesizeMax);设置单个上传文件的最大值 void setSizeMax(long sizeMax);设置上传温江总量的最大值</span></div><div class="line"><span class="comment">	 * void setHeaderEncoding();设置编码格式，解决上传文件名乱码问题</span></div><div class="line"><span class="comment">	 */</span></div><div class="line">	ServletFileUpload upload = <span class="keyword">new</span> ServletFileUpload(factory);</div><div class="line">	upload.setHeaderEncoding(<span class="string">"utf-8"</span>);<span class="comment">// 设置编码格式，解决上传文件名乱码问题</span></div><div class="line">	<span class="comment">/*</span></div><div class="line"><span class="comment">	 * 3、调用ServletFileUpload.parseRequest方法解析request对象,得到一个保存了所有上传内容的List对象</span></div><div class="line"><span class="comment">	 */</span></div><div class="line">	List&lt;FileItem&gt; parseRequest = <span class="keyword">null</span>;</div><div class="line">	<span class="keyword">try</span> &#123;</div><div class="line">		parseRequest = upload.parseRequest(request);</div><div class="line">	&#125; <span class="keyword">catch</span> (FileUploadException e) &#123;</div><div class="line">		e.printStackTrace();</div><div class="line">	&#125;</div><div class="line">	<span class="comment">/*</span></div><div class="line"><span class="comment">	 * 4、对list进行迭代，每迭代一个FileItem对象，调用其isFormField方法判断是否是文件上传</span></div><div class="line"><span class="comment">	 * true表示是普通表单字段，则调用getFieldName、getString方法得到字段名和字段值</span></div><div class="line"><span class="comment">	 * false为上传文件，则调用getInputStream方法得到数据输入流，从而读取上传数据</span></div><div class="line"><span class="comment">	 * FileItem用来表示文件上传表单中的一个上传文件对象或者普通的表单对象 该对象常用方法有： boolean</span></div><div class="line"><span class="comment">	 * isFormField();判断FileItem是一个文件上传对象还是普通表单对象 true表示是普通表单字段，</span></div><div class="line"><span class="comment">	 * 则调用getFieldName、getString方法得到字段名和字段值 false为上传文件，</span></div><div class="line"><span class="comment">	 * 则调用getName()获得上传文件的文件名，注意：有些浏览器会携带客户端路径，需要自己减除</span></div><div class="line"><span class="comment">	 * 调用getInputStream()方法得到数据输入流，从而读取上传数据 </span></div><div class="line"><span class="comment">	 * delete();表示在关闭FileItem输入流后，删除临时文件。</span></div><div class="line"><span class="comment">	 */</span></div><div class="line">	<span class="keyword">for</span> (FileItem fileItem : parseRequest) &#123;</div><div class="line">		<span class="keyword">if</span> (fileItem.isFormField()) &#123;<span class="comment">// 表示普通字段</span></div><div class="line">			<span class="keyword">if</span> (<span class="string">"username"</span>.equals(fileItem.getFieldName())) &#123;</div><div class="line">				String username = fileItem.getString();</div><div class="line">				writer.write(<span class="string">"您的用户名："</span> + username + <span class="string">"&lt;br&gt;"</span>);</div><div class="line">			&#125;</div><div class="line">			<span class="keyword">if</span> (<span class="string">"password"</span>.equals(fileItem.getFieldName())) &#123;</div><div class="line">				String userpass = fileItem.getString();</div><div class="line">				writer.write(<span class="string">"您的密码："</span> + userpass + <span class="string">"&lt;br&gt;"</span>);</div><div class="line">			&#125;</div><div class="line">		&#125; <span class="keyword">else</span> &#123;<span class="comment">// 表示是上传的文件</span></div><div class="line">				<span class="comment">// 不同浏览器上传的文件可能带有路径名，需要自己切割</span></div><div class="line">			String clientName = fileItem.getName();</div><div class="line">			String filename = <span class="string">""</span>;</div><div class="line">			<span class="keyword">if</span> (clientName.contains(<span class="string">"\\\\\\\\"</span>)) &#123;<span class="comment">// 如果包含"\\\\"表示是一个带路径的名字,则截取最后的文件名</span></div><div class="line">				filename = clientName.substring(clientName.lastIndexOf(<span class="string">"\\\\\\\\"</span>)).substring(<span class="number">1</span>);</div><div class="line">			&#125; <span class="keyword">else</span> &#123;</div><div class="line">				filename = clientName;</div><div class="line">			&#125;</div><div class="line">			UUID randomUUID = UUID.randomUUID();<span class="comment">// 生成一个128位长的全球唯一标识</span></div><div class="line">			filename = randomUUID.toString() + filename;</div><div class="line">			<span class="comment">/*</span></div><div class="line"><span class="comment">			 * 设计一个目录生成算法，如果所用用户上传的文件总数是亿数量级的或更多，放在同一个目录下回导致文件索引非常慢，</span></div><div class="line"><span class="comment">			 * 所以，设计一个目录结构来分散存放文件是非常有必要，且合理的 将UUID取哈希算法，散列到更小的范围，</span></div><div class="line"><span class="comment">			 * 将UUID的hashcode转换为一个8位的8进制字符串，</span></div><div class="line"><span class="comment">			 * 从这个字符串的第一位开始，每一个字符代表一级目录，这样就构建了一个八级目录，每一级目录中最多有16个子目录</span></div><div class="line"><span class="comment">			 * 这无论对于服务器还是操作系统都是非常高效的目录结构</span></div><div class="line"><span class="comment">			 */</span></div><div class="line">			<span class="keyword">int</span> hashUUID = randomUUID.hashCode();</div><div class="line">			String hexUUID = Integer.toHexString(hashUUID);</div><div class="line">			<span class="comment">// System.out.println(hexUUID);</span></div><div class="line">			<span class="comment">// 获取将上传的文件存存储在哪个文件夹下的绝对路径</span></div><div class="line">			String filepath = request.getSession().getServletContext().getRealPath(<span class="string">"upload"</span>);</div><div class="line">			System.out.println(<span class="string">"filePath="</span>+filepath);</div><div class="line">			<span class="keyword">for</span> (<span class="keyword">char</span> c : hexUUID.toCharArray()) &#123;</div><div class="line">				filepath = filepath + <span class="string">"/"</span> + c;</div><div class="line">			&#125;</div><div class="line">			<span class="comment">// 如果目录不存在就生成八级目录</span></div><div class="line">			File filepathFile = <span class="keyword">new</span> File(filepath);</div><div class="line">			<span class="keyword">if</span> (!filepathFile.exists()) &#123;</div><div class="line">				filepathFile.mkdirs();</div><div class="line">			&#125;</div><div class="line">			<span class="comment">// 从Request输入流中读取文件，并写入到服务器</span></div><div class="line">			InputStream inputStream2 = fileItem.getInputStream();</div><div class="line">			<span class="comment">// 在服务器端创建文件</span></div><div class="line">			File file = <span class="keyword">new</span> File(filepath + <span class="string">"/"</span> + filename);</div><div class="line">			BufferedOutputStream bos = <span class="keyword">new</span> BufferedOutputStream(<span class="keyword">new</span> FileOutputStream(file));</div><div class="line">			<span class="keyword">byte</span>[] buffer = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">10</span> * <span class="number">1024</span>];</div><div class="line">			<span class="keyword">int</span> len = <span class="number">0</span>;</div><div class="line">			<span class="keyword">while</span> ((len = inputStream2.read(buffer, <span class="number">0</span>, <span class="number">10</span> * <span class="number">1024</span>)) != -<span class="number">1</span>) &#123;</div><div class="line">				bos.write(buffer, <span class="number">0</span>, len);</div><div class="line">			&#125;</div><div class="line">			writer.write(<span class="string">"您上传文件"</span> + clientName + <span class="string">"成功&lt;br&gt;"</span>);</div><div class="line">			<span class="comment">// 关闭资源</span></div><div class="line">			bos.close();</div><div class="line">			inputStream2.close();</div><div class="line">		&#125;</div><div class="line">	&#125;</div><div class="line">	<span class="comment">// 注意Eclipse的上传的文件是保存在项目的运行目录，而不是workspace中的工程目录里。</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>其实很简单就是一个servelt,利用了commons-fileupload.jar和commons-io.jar两个库来实现，两个库网上都可以找到</p>
<ul>
<li>文件下载</li>
</ul>
<p>可以采用OKHTTP下载文件的方式，利用<code>ResponseBody</code>对象，调用<code>response.body().byteStream()</code>方法获取InputStream输入流，通过写文件操作来实现。</p>
<ul>
<li>同步请求和结合RxJava的使用</li>
</ul>
<p>1、同步请求</p>
<p><code>Call.execute()</code>同步请求网络，要注意的是Android4.0以后不能在主线程里调用，要开一个异步线程来使用，<br><code>Call.enqueue()</code>异步请求网络，加入一个回调，同步异步需要可按照不同的场景来使用。<br><code>Call.cancel()</code>取消此次请求，有一些场景还是会用到该方法的。</p>
<p>2、结合RxJava使用</p>
<p>添加RxJava环境，在builde.gradle里面添加上</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line">compile <span class="string">'io.reactivex:rxandroid:1.2.1'</span></div><div class="line">compile <span class="string">'io.reactivex:rxjava:1.1.6'</span></div><div class="line">compile <span class="string">'com.squareup.retrofit2:adapter-rxjava:2.1.0'</span></div></pre></td></tr></table></figure>
<p>我们就拿上面post异步请求改成RxJava模式</p>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="meta">@POST</span>(<span class="string">"query"</span>)</div><div class="line"><span class="function">Observable&lt;PostQueryInfo&gt; <span class="title">searchRx</span><span class="params">(@Query(<span class="string">"type"</span>)</span> String type, @<span class="title">Query</span><span class="params">(<span class="string">"postid"</span>)</span> String postid)</span>;</div></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="code"><pre><div class="line">Retrofit retrofit = new Retrofit.Builder()</div><div class="line">        .baseUrl(&quot;http://www.kuaidi100.com/&quot;)</div><div class="line">         //添加数据解析ConverterFactory</div><div class="line">        .addConverterFactory(GsonConverterFactory.create()) </div><div class="line">         //添加RxJava</div><div class="line">        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())   </div><div class="line">        .build();</div><div class="line">GitHubService apiService = retrofit.create(GitHubService.class);</div><div class="line">apiService.searchRx(&quot;yuantong&quot;,&quot;500379523313&quot;)</div><div class="line">		//访问网络切换异步线程</div><div class="line">        .subscribeOn(Schedulers.io())</div><div class="line">        //响应结果处理切换成主线程</div><div class="line">        .observeOn(AndroidSchedulers.mainThread())</div><div class="line">        .subscribe(new Subscriber&lt;PostQueryInfo&gt;() &#123;</div><div class="line">            @Override</div><div class="line">            public void onCompleted() &#123;</div><div class="line">            	 //请求结束回调</div><div class="line">            &#125;</div><div class="line">            @Override</div><div class="line">            public void onError(Throwable e) &#123;</div><div class="line">            	 //错误回调</div><div class="line">                e.printStackTrace();</div><div class="line">            &#125;</div><div class="line">            @Override</div><div class="line">            public void onNext(PostQueryInfo postQueryInfo) &#123;</div><div class="line">            	 //成功结果返回</div><div class="line">                Log.e(&quot;APP&quot;,postQueryInfo.getNu());</div><div class="line">            &#125;</div><div class="line">        &#125;);</div></pre></td></tr></table></figure>
<p>可能有些童鞋没接触过RxJava，这里了解一下就可以，后面我会单独写一篇关于RxJava的文章，到时可以再回来看看。</p>
<h3 id="配置设置"><a href="#配置设置" class="headerlink" title="配置设置"></a>配置设置</h3><ul>
<li>配置OKHttp</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line">HttpLoggingInterceptor interceptor = <span class="keyword">new</span> HttpLoggingInterceptor();</div><div class="line">interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);</div><div class="line">OkHttpClient client = <span class="keyword">new</span> OkHttpClient.Builder()</div><div class="line">				.connectTimeout(<span class="number">10000L</span>,TimeUnit.MILLISECONDS)       <span class="comment">//设置连接超时</span></div><div class="line">                .readTimeout(<span class="number">10000L</span>,TimeUnit.MILLISECONDS)          <span class="comment">//设置读取超时</span></div><div class="line">                .writeTimeout(<span class="number">10000L</span>,TimeUnit.MILLISECONDS)         <span class="comment">//设置写入超时</span></div><div class="line">                .cache(<span class="keyword">new</span> Cache(getCacheDir(),<span class="number">10</span> * <span class="number">1024</span> * <span class="number">1024</span>))   <span class="comment">//设置缓存目录和10M缓存</span></div><div class="line">                .addInterceptor(interceptor)	<span class="comment">//添加日志拦截器（该方法也可以设置公共参数，头信息）</span></div><div class="line">                .build();</div><div class="line">Retrofit retrofit = <span class="keyword">new</span> Retrofit.Builder()</div><div class="line">				.client(client)		<span class="comment">//设置OkHttp</span></div><div class="line">                .baseUrl(<span class="string">"http://www.kuaidi100.com/"</span>)</div><div class="line">                .addConverterFactory(GsonConverterFactory.create()) <span class="comment">//  添加数据解析ConverterFactory</span></div><div class="line">                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())   <span class="comment">//添加RxJava</span></div><div class="line">                .build();</div><div class="line">...省略后面的代码</div></pre></td></tr></table></figure>
<p>日志拦截器需要添加OkHttp对应库,okhttp的库是3.4.1，这里也需要设成3.4.1</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line">compile <span class="string">'com.squareup.okhttp3:logging-interceptor:3.4.1'</span></div></pre></td></tr></table></figure>
<ul>
<li>多种ConverterFactory设置</li>
</ul>
<p>常见的ConverterFactory有</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line">Gson: com.squareup.retrofit2:converter-gson:<span class="number">2.1</span><span class="number">.0</span></div><div class="line">Jackson: com.squareup.retrofit2:converter-jackson:<span class="number">2.1</span><span class="number">.0</span></div><div class="line">Moshi: com.squareup.retrofit2:converter-moshi:<span class="number">2.1</span><span class="number">.0</span></div><div class="line">Protobuf: com.squareup.retrofit2:converter-protobuf:<span class="number">2.1</span><span class="number">.0</span></div><div class="line">Wire: com.squareup.retrofit2:converter-wire:<span class="number">2.1</span><span class="number">.0</span></div><div class="line">Simple XML: com.squareup.retrofit2:converter-simplexml:<span class="number">2.1</span><span class="number">.0</span></div><div class="line">Scalars (primitives, boxed, and <span class="built_in">String</span>): com.squareup.retrofit2:converter-scalars:<span class="number">2.1</span><span class="number">.0</span></div></pre></td></tr></table></figure>
<p>添加对应得ConverterFactory只需要先在builde.gradle里面配置好上面对应的库，然后通过<code>.addConverterFactory</code>该方法添加即可</p>
<ul>
<li>添加混淆</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line">#Platform calls Class.forName on types which do not exist on Android to determine platform.</div><div class="line">-dontnote retrofit2.Platform</div><div class="line">#Platform used when running on RoboVM on iOS. Will not be used at runtime.</div><div class="line">-dontnote retrofit2.Platform$IOS$MainThreadExecutor</div><div class="line">#Platform used when running on Java 8 VMs. Will not be used at runtime.</div><div class="line">-dontwarn retrofit2.Platform$Java8</div><div class="line">#Retain generic type information for use by reflection by converters and adapters.</div><div class="line">-keepattributes Signature</div><div class="line">#Retain declared checked exceptions for use by a Proxy instance.</div><div class="line">-keepattributes Exceptions</div></pre></td></tr></table></figure>
<h3 id="介绍两个好用好玩的AS插件"><a href="#介绍两个好用好玩的AS插件" class="headerlink" title="介绍两个好用好玩的AS插件"></a>介绍两个好用好玩的AS插件</h3><p>1、GsonFormat JSON解析成对象<br>2、Sexy Editor 工作区间背景设置<br>都可以在Preferences下Plugins里搜索到</p>
<blockquote>
<p>写在最后的话：<br>这篇文章还是花了蛮长时间的，包括期间有一些其它事情耽搁了，加上还是边学边写变测试，虽然花的时间有点长但是我觉得还是学到了蛮多东西的，我相信我能一直坚持学下去，一直写下去。篇幅有点长谢谢大家能够看到最后！</p>
</blockquote>
<p><strong>成功源于不断的学习和积累</strong></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Android/" rel="tag"># Android</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/08/17/2016-08-17-okhttp/" rel="next" title="你必须学会的okhttp3.0入门篇">
                <i class="fa fa-chevron-left"></i> 你必须学会的okhttp3.0入门篇
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/09/05/2016-09-06-mvp/" rel="prev" title="你应该学会的设计模式MVP">
                你应该学会的设计模式MVP <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.png"
               alt="Soaic" />
          <p class="site-author-name" itemprop="name">Soaic</p>
           
              <p class="site-description motion-element" itemprop="description">Welcome!</p>
           
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives/">
                <span class="site-state-item-count">10</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">1</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">3</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#优点："><span class="nav-number">1.</span> <span class="nav-text">优点：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#缺点："><span class="nav-number">2.</span> <span class="nav-text">缺点：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#相关学习资料的网址"><span class="nav-number">3.</span> <span class="nav-text">相关学习资料的网址</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#环境配置"><span class="nav-number">4.</span> <span class="nav-text">环境配置</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#基本使用"><span class="nav-number">5.</span> <span class="nav-text">基本使用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#配置设置"><span class="nav-number">6.</span> <span class="nav-text">配置设置</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#介绍两个好用好玩的AS插件"><span class="nav-number">7.</span> <span class="nav-text">介绍两个好用好玩的AS插件</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2016 - 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Soaic</span>
</div>

<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

<div class="powered-by">
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_uv">
  本站访客数:<span id="busuanzi_value_site_uv"></span>
</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>


        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  






  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("nSNhFcJCeysT9vRXgfNvtbQF-gzGzoHsz", "aegQNi8pntiOE4R2z0e5B84D");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  

  

  

</body>
</html>
